package com.partsoft.dits.message;

import java.sql.Types;

import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

import com.partsoft.dits.DataEdgeDescriptor;

public class DataProperty implements Cloneable, DataEdgeDescriptor {
	
	public static final int DEFAULT_VALUE_SIZE = 128;
	
	public static final DataProperty DATA_ACTION = new DataProperty("__ACTION__", Types.VARCHAR);

	private String propertyName;
	
	private Integer valueType;
	
	private Integer valueSize;
	
	private int ordinal = 0;
	
	public DataProperty() {}
	
	public DataProperty(String columnName) {
		setPropertyName(columnName);
	}
	
	public DataProperty(String columnName, Integer columnType) {
		setPropertyName(columnName);
		setValueType(columnType);
	}
	
	public DataProperty(String columnName, Integer columnType, Integer columnSize) {
		setPropertyName(columnName);
		setValueType(columnType);
		setValueSize(columnSize);
	}
	
	public String getPropertyName() {
		return propertyName;
	}
	
	public int getOrdinal() {
		return ordinal;
	}

	public void setOrdinal(int ordinal) {
		this.ordinal = ordinal;
	}

	public void setPropertyName(String propertyName) {
		Assert.hasText(propertyName, "Must be set property name");
		this.propertyName = propertyName;
	}

	public Integer getValueType() {
		return valueType == null ? Types.VARCHAR : valueType;
	}

	public void setValueType(Integer valueType) {
		this.valueType = valueType;
	}

	public Integer getValueSize() {
		return valueSize == null ? DEFAULT_VALUE_SIZE : valueSize;
	}

	public void setValueSize(Integer valueSize) {
		this.valueSize = valueSize;
	}
	
	public String getTitle() {
		return new StringBuilder("property name is \"").append(getPropertyName()).append("\"").toString();
	}

	public String getDescription() {
		return getTitle();
	}

	public String getId() {
		return getPropertyName();
	}

	public String getMessageCode() {
		return getPropertyName();
	}

	@Override
	public DataProperty clone() {
		try {
			return (DataProperty) super.clone();
		} catch (CloneNotSupportedException e) {
			return null;
		}
	}
	
	public String getDataIdentityPrefix() {
		return null;
	}

	@Override
	public String toString() {
		return "DataProperty(propertyName=" + getPropertyName() + ", valueType=" + getValueType() + ", valueSize=" + getValueSize() + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((propertyName == null) ? 0 : propertyName.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!ClassUtils.isAssignableValue(getClass(), obj))
			return false;
		DataProperty other = (DataProperty) obj;
		if (getPropertyName() == null) {
			if (other.getPropertyName() != null)
				return false;
		} else if (!getPropertyName().equalsIgnoreCase(other.getPropertyName()))
			return false;
		return true;
	}
	
}
